﻿using System;
using System.Linq;
using System.ComponentModel;
using System.IO;
using Esponce.QRCode;
using Microsoft.Win32;

namespace Esponce.Models
{
	public class TrackImportViewModel : INotifyPropertyChanged
	{
		#region Public properties
		public string FilePath
		{
			get
			{
				return this.filePath;
			}
			set
			{
				if (this.filePath != value)
				{
					this.filePath = value;
					OnPropertyChanged("FilePath");
				}
			}
		}
		private string filePath;

		public ImportFormat Format
		{
			get
			{
				if (this.FileExtension == null)
				{
					return ImportFormat.CSV;
				}

				string ext = this.FileExtension.ToLower();
				switch (ext)
				{
					case ".csv":
						return ImportFormat.CSV;

					case ".xls":
						return ImportFormat.XLS;

					case ".xml":
						return ImportFormat.XML;

					case ".json":
						return ImportFormat.JSON;

					case ".zip":
						return ImportFormat.ZIP_PNG;
				}

				return ImportFormat.CSV;
			}
		}

		public string FileExtension
		{
			get
			{
				if (!string.IsNullOrEmpty(this.FilePath))
				{
					return Path.GetExtension(this.FilePath);
				}
				return null;
			}
		}

		public bool IsLoading
		{
			get
			{
				return this.isLoading;
			}
			set
			{
				if (this.isLoading != value)
				{
					this.isLoading = value;
					OnPropertyChanged("IsLoading");
				}
			}
		}
		private bool isLoading;
		#endregion

		#region Public methods
		public void Browse()
		{
			OpenFileDialog dialog = new OpenFileDialog();
			dialog.Filter = "Import (*.csv, *.xls, *.xml, *.json, *.zip)|*.csv;*.xls;*.xml;*.json;*.zip";
			dialog.DefaultExt = "*.*";

			if (dialog.ShowDialog() == true)
			{
				this.FilePath = dialog.FileName;
			}
		}

		public void Import()
		{
			try
			{
				if (string.IsNullOrEmpty(this.FilePath) || !File.Exists(this.FilePath))
				{
					throw new Exception("Input file does not exist!");
				}

				//Start the loading animation for better UX
				this.IsLoading = true;

				var client = App.ViewModel.CreateClient();
				App.Logger.WriteLine("POST " + client.UriBuilder.BuildTrackImportUrl(this.Format));

				var stream = File.OpenRead(this.FilePath);

				client.ImportTrackRecordsCompleted += (sender, e) =>
				{
					//Stop the loading animation
					this.IsLoading = false;

					try
					{
						if (e.Error != null)
						{
							throw e.Error;
						}

						if (e.Results != null)
						{
							int warnings = e.Results.Count(x => !string.IsNullOrEmpty(x.Warning));
							int errors = e.Results.Count(x => !string.IsNullOrEmpty(x.Error));
							if (warnings > 0 || errors > 0)
							{
								App.Logger.Log(new Exception(string.Format("{0} warnings, {1} errors", warnings, errors)));
							}
						}

						App.Logger.WriteLine("Import completed: " + this.FilePath);
					}
					catch (Exception ex)
					{
						//Report error to the console
						App.Logger.Log(ex);
					}
					finally
					{
						stream.Close();
					}
				};
				client.ImportTrackRecordsAsync(stream, this.Format);
			}
			catch (Exception ex)
			{
				App.Logger.Log(ex);
			}
		}
		#endregion

		#region INotifyPropertyChanged Members
		public event PropertyChangedEventHandler PropertyChanged;
		protected virtual void OnPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}
		#endregion
	}
}
